<template>
    <div class="container-fluid p-4">
        <!-- 考核统计 -->
        <el-row :gutter="20" class="mb-4">
            <el-col :span="6">
                <el-card shadow="never">
                    <div class="d-flex align-items-center">
                        <div class="flex-shrink-0">
                            <div class="bg-primary bg-gradient text-white rounded-circle p-3">
                                <i class="bi bi-clipboard-check"></i>
                            </div>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <h6 class="mb-1">已完成考核</h6>
                            <h4 class="mb-0">{{ completedCount }}</h4>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card shadow="never">
                    <div class="d-flex align-items-center">
                        <div class="flex-shrink-0">
                            <div class="bg-warning bg-gradient text-white rounded-circle p-3">
                                <i class="bi bi-hourglass-split"></i>
                            </div>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <h6 class="mb-1">待完成考核</h6>
                            <h4 class="mb-0">{{ pendingCount }}</h4>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card shadow="never">
                    <div class="d-flex align-items-center">
                        <div class="flex-shrink-0">
                            <div class="bg-success bg-gradient text-white rounded-circle p-3">
                                <i class="bi bi-award"></i>
                            </div>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <h6 class="mb-1">平均分数</h6>
                            <h4 class="mb-0">{{ assessmentStatistics.averageScore }}</h4>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card shadow="never">
                    <div class="d-flex align-items-center">
                        <div class="flex-shrink-0">
                            <div class="bg-info bg-gradient text-white rounded-circle p-3">
                                <i class="bi bi-graph-up"></i>
                            </div>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <h6 class="mb-1">考核通过率</h6>
                            <h4 class="mb-0">{{ assessmentStatistics.passRate }}%</h4>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 待完成考核 -->
        <el-row :gutter="20" class="mb-4">
            <el-col :span="24">
                <el-card shadow="never">
                    <template #header>
                        <div class="card-header">
                            <h5 class="mb-0">待完成考核</h5>
                        </div>
                    </template>
                    <el-table :data="pendingAssessments" style="width: 100%">
                        <el-table-column prop="exam.title" label="考核名称"></el-table-column>
                        <el-table-column prop="examSection.name" label="类型">
                            <template #default="scope">
                                <el-tag :type="scope.row.examSection.name === '理论考核' ? 'primary' : 'success'">
                                    {{ scope.row.examSection.name }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="exam.endTime" label="截止时间"><template #default="{ row }">
                                {{ formatDate(row.exam.endTime) }}
                            </template></el-table-column>
                        <el-table-column label="状态">
                            <template #default>
                                <el-tag type="warning">未完成</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button type="primary" size="small" @click="startAssessment(scope.row)">开始考核
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
            </el-col>
        </el-row>

        <!-- 历史考核记录 -->
        <el-row :gutter="20">
            <el-col :span="24">
                <el-card shadow="never">
                    <template #header>
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">历史考核记录</h5>
                            <div class="d-flex">
                                <el-select v-model="historyTypeFilter" placeholder="全部类型" size="small" class="me-2">
                                    <el-option label="全部类型" value="all"></el-option>
                                    <el-option label="理论考试" value="理论考试"></el-option>
                                    <el-option label="实操考核" value="实操考核"></el-option>
                                    <el-option label="案例分析" value="案例分析"></el-option>
                                </el-select>
                                <el-select v-model="historyTimeFilter" placeholder="最近三个月" size="small">
                                    <el-option label="最近三个月" value="3months"></el-option>
                                    <el-option label="最近半年" value="6months"></el-option>
                                    <el-option label="最近一年" value="1year"></el-option>
                                    <el-option label="全部时间" value="all"></el-option>
                                </el-select>
                            </div>
                        </div>
                    </template>
                    <el-table :data="filteredHistoryAssessments" style="width: 100%">
                        <el-table-column prop="exam.title" label="考核名称"></el-table-column>
                        <el-table-column prop="examSection.name" label="类型">
                            <template #default="scope">
                                <el-tag :type="scope.row.examSection.name === '理论考核' ? 'primary' : 'success'">
                                    {{ scope.row.examSection.name }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="submission.submitTime" label="完成时间">
                            <template #default="{ row }">
                                {{ row.submission ? new Date(row.submission.submitTime).toLocaleString() : 'N/A' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="submission.totalScore" label="得分">
                            <template #default="{ row }">
                                {{ row.submission?.totalScore ?? '待批改' }}
                            </template>
                        </el-table-column>

                        <el-table-column label="状态">
                            <template #default="{ row }">
                                <el-tag :type="getHistoryStatus(row.submission).type">
                                    {{ getHistoryStatus(row.submission).text }}
                                </el-tag>
                            </template>
                        </el-table-column>

                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button type="info" size="small" plain
                                    @click="viewAssessmentDetail(scope.row)">查看详情</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="pagination-container mt-4">
                        <el-pagination background layout="prev, pager, next" :total="historyAssessments.length"
                            :page-size="10" :current-page="1" />
                    </div>
                </el-card>
            </el-col>
        </el-row>
    </div>
    <SubmissionDetailModal v-model="isDetailModalVisible" :submission-data="currentSubmissionDetail" />
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from 'vue-router';
import { useExamStore } from '@/stores/exam.js';
import { useUserStore } from '@/stores/user.js';
import { storeToRefs } from 'pinia';
import { ElMessage } from "element-plus";
import SubmissionDetailModal from '@/components/alert/student/SubmissionDetailModal.vue'; // 1. 导入弹窗组件

// --- 初始化 ---
const router = useRouter();
const examStore = useExamStore();
const userStore = useUserStore();

const isDetailModalVisible = ref(false);
const currentSubmissionDetail = ref(null);

// 从 examStore 中获取响应式的考核列表和加载状态
const { loading } = storeToRefs(examStore);

// --- 新增：用于存储从新接口获取的数据 ---
const pendingAssessments = ref([]);
const historyAssessments = ref([]);

const mockApiResponse = {
    "code": 200,
    "data": {
        "completeExam": [{
            "exam": { "id": 10, "title": "2023年护理基础入门期中考试", "status": "completed", /* ...其他字段... */ },
            "examSection": { "name": "理论考核" }
        },
        {
            "exam": { "id": 10, "title": "2023年护理基础入门期中考试", "status": "completed", /* ...其他字段... */ },
            "examSection": { "name": "理论考核" }
        },
        {
            "exam": { "id": 10, "title": "2023年护理基础入门期中考试", "status": "completed", /* ...其他字段... */ },
            "examSection": { "name": "理论考核" }
        }
        ],
        "unCompleteExam": [
            {
                "exam": { "id": 1, "title": "护理基础理论测试", "status": "published", "endTime": "2025-07-10T02:30:00.000+00:00", /* ... */ },
                "examSection": { "name": "理论考核" }
            },
            {
                "exam": { "id": 2, "title": "伤口护理技能考核", "status": "published", "endTime": "2025-07-15T08:00:00.000+00:00", /* ... */ },
                "examSection": { "name": "实操考核" }
            },
            {
                "exam": { "id": 10, "title": "测试考核", "status": "published", "endTime": "2025-07-15T08:00:00.000+00:00", /* ... */ },
                "examSection": { "name": "实操考核" }
            }
        ]
    }
};

const mockSubmissionResponse = {
    examSubmission: {
        submitTime: "2025-07-01T09:26:41.000+00:00",
        totalScore: 88.5,
        gradingStatus: "completed"
    }
};

const formatDate = (dateString) => {
    if (!dateString) return "N/A"; // 如果日期为空，返回 'N/A'
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");

    // 返回 "年-月-日 时:分" 格式
    return `${year}-${month}-${day} ${hours}:${minutes}`;
};
// 新增：根据答卷信息判断历史考核的状态
const getHistoryStatus = (submission) => {
    // 如果没有答卷信息，说明未提交
    if (!submission) {
        return { text: '未提交', type: 'info' };
    }

    // 根据后端返回的批改状态进行判断
    switch (submission.gradingStatus) {
        case 'completed':
            // 如果已完成批改，则根据分数判断是否通过
            return submission.totalScore < 60
                ? { text: '不通过', type: 'danger' }
                : { text: '通过', type: 'success' };
        case 'pending':
        case 'in_progress':
            // 如果是待处理或处理中
            return { text: '处理中', type: 'warning' };
        default:
            // 其他未知状态
            return { text: '未知', type: 'info' };
    }
};
// --- 生命周期 ---
onMounted(() => {
    //调用新接口获取学生的所有考核
    examStore.fetchCurrentUserExams((data) => {
        if (data) {
            // 将未完成的考核直接赋值
            pendingAssessments.value = data.unCompleteExam || [];

            // 对于已完成的考核，需要进一步获取答卷信息
            fetchSubmissionsForCompletedExams(data.completeExam || []);
        }
    });
    // console.log("使用Mock数据进行页面初始化...");
    // const data = mockApiResponse.data;
    // if (data) {
    //     pendingAssessments.value = data.unCompleteExam || [];
    //     fetchSubmissionsForCompletedExams(data.completeExam || []);
    // }
});

const fetchSubmissionsForCompletedExams = async (completedExams) => {
    // --- 修改开始 ---
    // 不再并行请求，而是为每个已完成的考核附加一个伪造的答卷信息
    // console.log("为已完成的考核附加Mock答卷数据...");
    // const historyData = completedExams.map(examData => {
    //     return {
    //         ...examData,
    //         submission: mockSubmissionResponse.examSubmission // 直接使用伪造的答卷数据
    //     };
    // });

    // historyAssessments.value = historyData;

    /**
     * 不要删！！！这里是写好的接口，但是因为还没实现，修改为用上面的假数据
     */

    if (!userStore.user?.id) {
        console.error("无法获取当前学生ID");
        return;
    }

    // 使用 Promise.all 来并行请求所有已完成考核的答卷信息
    const submissionPromises = completedExams.map(examData => {
        return new Promise((resolve) => {
            examStore.fetchSubmissions(
                { examId: examData.exam.id, studentId: userStore.user.id },
                (submissionData) => {
                    // 将获取到的答卷信息 (submission) 合并到原始的考核数据中
                    resolve({ ...examData, submission: submissionData?.examSubmission });
                }
            );
        });
    });

    // 等待所有请求完成后，更新历史考核列表
    historyAssessments.value = await Promise.all(submissionPromises);
};

/**
* 不要删！！！这里是写好的接口，但是因为还没实现，修改为用上面的假数据
*/

// // --- 计算属性 ---
// // 筛选出待完成的考核（例如：已发布但学生尚未提交）
// const pendingAssessments = computed(() => {
//     if (!Array.isArray(exams.value)) return [];
//     // 这里的过滤逻辑需要根据你的业务来定
//     // 假设'published'状态的考核是待完成的
//     return exams.value.filter(item => item.exam.status === 'published');
// });

// // 筛选出已完成的考核（需要查询 submission 记录来判断，这里先简化）
// const historyAssessments = computed(() => {
//     if (!Array.isArray(exams.value)) return [];
//     // 假设'ended'或学生已提交的为历史考核，这里先用非'published'代替
//     return exams.value.filter(item => item.exam.status !== 'published');
// });


// 考核统计数据
const assessmentStats = ref([
    {
        title: "总考核数",
        value: 120,
        icon: "i-bi-journal-check",
        color: "text-primary",
    },
    {
        title: "已完成",
        value: 100,
        icon: "i-bi-check-circle",
        color: "text-success",
    },
    {
        title: "待完成",
        value: 20,
        icon: "i-bi-hourglass-split",
        color: "text-warning",
    },
    { title: "平均得分", value: 85, icon: "i-bi-award", color: "text-info" },
]);

// 计算待完成考核的数量
const pendingCount = computed(() => pendingAssessments.value.length);

// 计算已完成考核的数量
const completedCount = computed(() => historyAssessments.value.length);

// 计算平均分数
// const averageScore = computed(() => {
//     // 1. 从历史记录中，筛选出所有状态为 'completed' 并且有分数的考核
//     const gradedAssessments = historyAssessments.value.filter(
//         item => item.submission &&
//             item.submission.gradingStatus === 'completed' &&
//             typeof item.submission.totalScore === 'number'
//     );

//     // 2. 如果没有已评分的考核，则返回 0
//     if (gradedAssessments.length === 0) {
//         return 0;
//     }

//     // 3. 计算总分
//     const totalScoreSum = gradedAssessments.reduce(
//         (sum, item) => sum + item.submission.totalScore,
//         0
//     );

//     // 4. 计算平均分并保留一位小数
//     const avg = totalScoreSum / gradedAssessments.length;
//     return avg.toFixed(1);
// });
// ... 其他代码 ...

const assessmentStatistics = computed(() => {
    // 1. 筛选出所有已完成批改并且有分数的历史考核记录
    const gradedAssessments = historyAssessments.value.filter(
        item => item.submission &&
            item.submission.gradingStatus === 'completed' &&
            typeof item.submission.totalScore === 'number'
    );

    // 2. 如果没有已评分的考核，则返回默认值
    if (gradedAssessments.length === 0) {
        return {
            averageScore: '0.0',
            passRate: '0.0'
        };
    }

    // 3. 计算总分和平均分
    const totalScoreSum = gradedAssessments.reduce(
        (sum, item) => sum + item.submission.totalScore,
        0
    );
    const averageScore = (totalScoreSum / gradedAssessments.length).toFixed(1);
    // 4. 计算通过的考核数量 (分数 >= 60)
    const passedCount = gradedAssessments.filter(
        item => item.submission.totalScore >= 60
    ).length;
    // 5. 计算通过率
    const passRate = ((passedCount / gradedAssessments.length) * 100).toFixed(1);

    // 6. 返回一个包含两个计算结果的对象
    return {
        averageScore,
        passRate
    };
});


// 历史考核筛选条件
const historyTypeFilter = ref("all");
const historyTimeFilter = ref("3months");

const filteredHistoryAssessments = computed(() => {
    let filtered = historyAssessments.value;

    if (historyTypeFilter.value !== "all") {
        filtered = filtered.filter((item) => item.type === historyTypeFilter.value);
    }

    // 实际项目中，这里需要根据 historyTimeFilter.value 进行日期过滤
    // 示例中简化处理，只做类型过滤

    return filtered;
});

const startAssessment = (assessment) => {
    ElMessage.info(`正在进入考核: ${assessment.exam.title}`);
    // 跳转到学生答题页面
    router.push(`/student/take-exam/${assessment.exam.id}`);
};

const viewAssessmentDetail = (assessmentRow) => {
    // 从 assessmentRow 中获取需要的数据
    // 注意：这里的 studentId 需要从 userStore 中获取当前登录的用户ID
    const examId = assessmentRow.exam.id;
    const studentId = userStore.user.id; // 假设 userStore 中有当前登录的用户信息

    if (!studentId) {
        ElMessage.error("无法获取当前用户信息，请重新登录！");
        return;
    }

    // 调用 store 中的 action 来获取答卷详情
    // URL: GET /api/exams/{examId}/submissions?studentId={studentId}
    examStore.fetchSubmissions(
        { examId, studentId },
        (data) => {
            if (data && data.examSubmission) {
                currentSubmissionDetail.value = data;
                isDetailModalVisible.value = true;
            } else {
                ElMessage.warning("暂未查询到您的答卷记录。");
            }
        }
    );
};
</script>
<style scoped>
.assessment-container {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 18px 20px;
    border-bottom: 1px solid var(--el-card-border-color);
    box-sizing: border-box;
}

.stat-card .el-card__body {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.stat-icon {
    font-size: 2.5rem;
}

.stat-value {
    font-size: 2rem;
    font-weight: bold;
}

.stat-title {
    font-size: 1rem;
    color: #6c757d;
}

.el-table {
    margin-top: 20px;
}

.pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

/* Bootstrap Icons compatibility */
[class^="i-bi-"] {
    display: inline-block;
    width: 1em;
    height: 1em;
    background-size: 100% 100%;
    background-repeat: no-repeat;
}

.i-bi-journal-check {
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='currentColor' class='bi bi-journal-check' viewBox='0 0 16 16'%3E%3Cpath fill-rule='evenodd' d='M10.854 6.146a.5.5 0 0 1 0 .708l-3 3a.5.5 0 0 1-.708 0l-1.5-1.5a.5.5 0 1 1 .708-.708L7.5 8.793l2.646-2.647a.5.5 0 0 1 .708 0z'/%3E%3Cpath d='M3 0h10a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2v-1h1v1a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H3a1 1 0 0 0-1 1v1H1V2a2 2 0 0 1 2-2z'/%3E%3Cpath d='M1 5v-.5a.5.5 0 0 1 1 0V5h.5a.5.5 0 0 1 0 1h-.5v.5a.5.5 0 0 1-1 0V6h-.5a.5.5 0 0 1 0-1H1zm0 3v-.5a.5.5 0 0 1 1 0V8h.5a.5.5 0 0 1 0 1h-.5v.5a.5.5 0 0 1-1 0V9h-.5a.5.5 0 0 1 0-1H1zm0 3v-.5a.5.5 0 0 1 1 0v.5h.5a.5.5 0 0 1 0 1h-.5v.5a.5.5 0 0 1-1 0v-.5h-.5a.5.5 0 0 1 0-1H1z'/%3E%3C/svg%3E");
}

.i-bi-check-circle {
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='currentColor' class='bi bi-check-circle' viewBox='0 0 16 16'%3E%3Cpath d='M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z'/%3E%3Cpath d='M10.97 4.97a.235.235 0 0 0-.02.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-1.071-1.05z'/%3E%3C/svg%3E");
}

.i-bi-hourglass-split {
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='currentColor' class='bi bi-hourglass-split' viewBox='0 0 16 16'%3E%3Cpath d='M2.5 15a.5.5 0 1 1 0-1h11a.5.5 0 1 1 0 1h-11zm2-4a.5.5 0 0 1 .5-.5h6a.5.5 0 1 1 0 1h-6a.5.5 0 0 1-.5-.5zm2-3a.5.5 0 0 1 .5-.5h2a.5.5 0 1 1 0 1h-2a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h6a.5.5 0 1 1 0 1h-6a.5.5 0 0 1-.5-.5zM2.5 1a.5.5 0 1 0 0 1h11a.5.5 0 1 0 0-1h-11z'/%3E%3Cpath d='M2 1.5a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5zm.5 2.5a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5zm0 9a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5z'/%3E%3Cpath d='M8 10a3 3 0 1 0 0-6 3 3 0 0 0 0 6z'/%3E%3C/svg%3E");
}

.i-bi-award {
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='currentColor' class='bi bi-award' viewBox='0 0 16 16'%3E%3Cpath d='M9.669.864 8 0 6.331.864 4.735 3.059 2.913 2.424 2.882 4.356 1.541 5.686 2.5 7.56 1.913 9.656 3.61 9.932 4.735 11.94l1.602 2.124L8 16l1.602-2.124 1.125-2.018 1.707-.276 1.087-2.094 1.354-1.354L13.118 5.686l-1.333-1.927L9.669.864zm-.017 1.132L8 1.166l-1.652.83-.8 1.46-1.415-.493-.04.244-1.16 1.16-.702 1.35 1.086 1.086-.286 1.707 1.707.286.8 1.46 1.415.493.04-.244 1.16-1.16.702-1.35-1.086-1.086.286-1.707-1.707-.286-.8-1.46z'/%3E%3C/svg%3E");
}

.i-bi-play-circle {
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='currentColor' class='bi bi-play-circle' viewBox='0 0 16 16'%3E%3Cpath d='M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z'/%3E%3Cpath d='M6.271 5.055a.5.5 0 0 1 .52.038l3.5 2.5a.5.5 0 0 1 0 .814l-3.5 2.5A.5.5 0 0 1 6 10.5V5.5a.5.5 0 0 1 .271-.445z'/%3E%3C/svg%3E");
}

.i-bi-info-circle {
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='currentColor' class='bi bi-info-circle' viewBox='0 0 16 16'%3E%3Cpath d='M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z'/%3E%3Cpath d='m8.93 6.588-2.29.287-.082.38.45.083c.294.07.352.176.288.469l-.738 3.468c-.194.897.105 1.319.808 1.319.545 0 1.178-.252 1.465-.598l.088-.416c-.2.176-.492.246-.686.246-.275 0-.375-.193-.304-.533L8.93 6.588zM9 4.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0z'/%3E%3C/svg%3E");
}
</style>